import { waterRenderMaterial } from "./js/waterRender2.js"; // 导入着色器
const canvas = document.getElementById("renderCanvas"); // Get the canvas element
// 尝试获取 WebGL2 上下文
const gl = canvas.getContext("webgl2");
if (gl) {
  console.log("支持 WebGL 2.0");
} else {
  alert("设备不支持 WebGL 2.0");
}
// const vertexBuffer = new BABYLON.VertexBuffer()
const engine = new BABYLON.Engine(canvas, true, {
  alpha: true,
  antialias: true,
}); // Generate the BABYLON 3D engine
// engine.setAlphaMode(BABYLON.Engine.ALPHA_PREMULTIPLIED); // 设置透明模式
function showWorldAxis(size, scene) {
  const makeAxis = function (axis, color) {
    const axisMaterial = new BABYLON.StandardMaterial("axisMat", scene);
    axisMaterial.diffuseColor = color;
    axisMaterial.emissiveColor = color;

    const axisLine = BABYLON.MeshBuilder.CreateLines(
      "axis" + axis,
      {
        points: [
          BABYLON.Vector3.Zero(),
          axis === "X"
            ? new BABYLON.Vector3(size, 0, 0)
            : axis === "Y"
            ? new BABYLON.Vector3(0, size, 0)
            : new BABYLON.Vector3(0, 0, size),
        ],
      },
      scene
    );
    axisLine.color = color;
  };

  makeAxis("X", BABYLON.Color3.Red()); // 红色X轴
  makeAxis("Y", BABYLON.Color3.Green()); // 绿色Y轴
  makeAxis("Z", BABYLON.Color3.Blue()); // 蓝色Z轴
}
const createScene = async function () {
  // Creates a basic Babylon Scene object
  const scene = new BABYLON.Scene(engine);
  const camera = new BABYLON.ArcRotateCamera(
    "camera",
    0,
    0,
    0,
    new BABYLON.Vector3.Zero(),
    scene
  );
  // 设置旋转中心
  camera.setTarget(new BABYLON.Vector3(0, 0, 0));
  // 设置世界坐标位置（起点）
  camera.setPosition(new BABYLON.Vector3(0, 80, -10));
  camera.lowerBetaLimit = 0.01; // 避免完全俯视
  camera.upperBetaLimit = Math.PI - 0.01; // 避免翻转
  camera.attachControl(canvas, true);

  // Parameters: name, position, scene
  // const camera = new BABYLON.FlyCamera(
  //   "FlyCamera",
  //   new BABYLON.Vector3(0, 10, 0),
  //   scene
  // );
  // // Airplane like rotation, with faster roll correction and banked-turns.
  // // Default is 100. A higher number means slower correction.
  // // camera.maxZ = 1e7;
  // camera.rollCorrect = 10;
  // // Default is false.
  // camera.bankedTurn = true;
  // // Defaults to 90° in radians in how far banking will roll the camera.
  // camera.bankedTurnLimit = Math.PI / 2;
  // // How much of the Yawing (turning) will affect the Rolling (banked-turn.)
  // // Less than 1 will reduce the Rolling, and more than 1 will increase it.
  // camera.bankedTurnMultiplier = 1;

  // // This attaches the camera to the canvas
  // camera.attachControl(canvas, true);
  const time = performance.now();
  showWorldAxis(5, scene);

  //   depthRenderer = scene.enableDepthRenderer(camera);
  //   createPostProcess(camera, scene); // 后处理
  return scene;
};

const scene = await createScene(); //Call the createScene function
const light = new BABYLON.HemisphericLight(
  "light",
  new BABYLON.Vector3(1, 1, 0)
);
const plane = BABYLON.MeshBuilder.CreateGround(
  "plane",
  {
    width: 1000,
    height: 1000,
    subdivisionsX: 10,
    subdivisionsY: 10,
    doubleSided: true,
  },
  scene
); // 创建一个平面
// plane.rotation = new BABYLON.Vector3(Math.PI / 2, 0, 0);
let material = waterRenderMaterial(scene);
material.backFaceCulling = false;   // 关闭背面剔除，允许双面渲染
plane.material = material;
scene.addMesh(plane); // 将平面添加到场景中
// 这里的 "textures/grass.jpg" 可以换成你的图片路径
// const noiseTexture = new BABYLON.Texture("./texture/2048noise.png", scene);
const noiseTexture = new BABYLON.Texture("./texture/2048noise.png", scene);
scene.registerBeforeRender(() => {
  material.setFloat("time", performance.now() * 1e-3); // 设置时间
  // 设置屏幕分辨率
  material.setVector2(
    "iResolution",
    new BABYLON.Vector2(engine.getRenderWidth(), engine.getRenderHeight())
  );
  material.setTexture("noiseTexture", noiseTexture);
});
// Register a render loop to repeatedly render the scene
engine.runRenderLoop(function () {
  scene.render();
});
// Watch for browser/canvas resize events
window.addEventListener("resize", function () {
  engine.resize();
});
